package com.toidep.api;

import java.io.UnsupportedEncodingException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.toidep.R;
import com.toidep.activities.LoginActivity;
import com.toidep.activities.MainActivity;
import com.toidep.activities.SplashScreenActivity;
import com.toidep.config.Constants;
import com.toidep.interfaces.ResponseListener;
import com.toidep.network.AsyncHttpClient;
import com.toidep.network.AsyncHttpResponseHandler;
import com.toidep.network.RequestParams;
import com.toidep.payment.PaymentControl;
import com.toidep.preference.SharePreference;
import com.toidep.utilities.NetworkUtility;
import com.toidep.utilities.StringUtility;

public class ApiController {
	
	/**
	 * Ham gui request theo phuong thuc GET
	 * 
	 */
	public static void requestProcess(final String url,
			final Activity activity, final boolean isCancelAllRequest,
			final ResponseListener responseListener) {
		Log.e("requestProcess 1", url);

		if (NetworkUtility.getInstance(activity)
				.isNetworkAvailable()) {
			
		} else {
			if (activity != null) {
//				Toast.makeText(activity,"not network", 5000).show();
				responseListener.processResponse(-1);
				NetworkUtility.getInstance(activity).showAlert();
			}
			return;
		}
		
		AsyncHttpClient clientGet = new AsyncHttpClient();
		clientGet.get(url, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				Log.e("requestProcess", "onSuccess");
				if (!isValidToken(activity, content)) {
					((MainActivity)activity).setResponlistener(responseListener, url);
					Intent i = new Intent(activity, LoginActivity.class);
					i.putExtra("invalid_token", true);
					activity.startActivity(i);
					activity.finish();
//					activity.startActivityForResult(new Intent(activity, LoginActivity.class), Constants.REQUEST_CODE_VALID_TOKEN);
				} else {
					responseListener.processResponse(content);
				}
				
			}

			@Override
			public void onFailure(Throwable error, String content) {
				Log.e("requestProcess", "onFailure");
				
				responseListener.processResponse(-1);
			}
		});
	}
	
	public static void requestProcessLogin(final String url,
			final Activity activity, final boolean isCancelAllRequest,
			final ResponseListener responseListener) {
		Log.e("requestProcess 1", url);

		if (NetworkUtility.getInstance(activity)
				.isNetworkAvailable()) {
			
		} else {
			if (activity != null) {
//				Toast.makeText(activity,"not network", 5000).show();
				responseListener.processResponse(-1);
				NetworkUtility.getInstance(activity).showAlert();
			}
			return;
		}
		
		AsyncHttpClient clientGet = new AsyncHttpClient();
		clientGet.get(url, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				Log.e("requestProcess", "onSuccess");
				responseListener.processResponse(content);
				
			}

			@Override
			public void onFailure(Throwable error, String content) {
				Log.e("requestProcess", "onFailure");
				
				responseListener.processResponse(-1);
			}
		});
	}
	public static boolean isValidToken(Activity activity, String response) {
		try {
			if (!TextUtils.isEmpty(response) ) {
				JSONObject jsonObject = new JSONObject(response);
				if (jsonObject != null) {
					int code = ParseJSON.getIntValue(jsonObject, Constants.PARAM_RESPONSE_CODE);
					if (code == 0) {
						String message = ParseJSON.getStringValue(jsonObject, Constants.PARAM_RESPONSE_MESSAGE);
						if (message.equalsIgnoreCase("Login fail") || message.equalsIgnoreCase("Token invalid")) {
							Log.d("Parser", "messagge = " + message);
							return false;
						}
					}
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
			return true;
		}
		return true;
		
	}
	/**
	 * Ham gui request theo phuong thuc POST
	 * 
	 */
	public static void requestProcess(final String url, RequestParams parameters,
			final Activity activity, final boolean isCancelAllRequest,
			final ResponseListener responseListener) {
		Log.e("requestProcess 1", url);

		/*if (NetworkUtility.getInstance(activity.getBaseContext())
				.isNetworkAvailable()) {
			// Toast.makeText(activity, "You have Internet Connection",
			// Toast.LENGTH_LONG).show();
		} else {
			if (activity != null) {
//				Toast.makeText(activity, R.string.text_key_network_check, 5000).show();
				responseListener.processResponse(-1);
			}
			return;
		}*/
		
		AsyncHttpClient clientGet = new AsyncHttpClient();
		clientGet.post(activity, url, parameters, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				Log.e("requestProcess", "onSuccess");
				if (!isValidToken(activity, content)) {
					((MainActivity)activity).setResponlistener(responseListener, url);
					Intent i = new Intent(activity, LoginActivity.class);
					i.putExtra("invalid_token", true);
					activity.startActivity(i);
					activity.finish();
//					activity.startActivityForResult(new Intent(activity, LoginActivity.class), Constants.REQUEST_CODE_VALID_TOKEN);
				} else {
					responseListener.processResponse(content);
				}
//				responseListener.processResponse(content);
			}

			@Override
			public void onFailure(Throwable error, String content) {
				Log.e("requestProcess", "onFailure: error=" + error.getMessage() + "content= " + content);
				
				responseListener.processResponse(-1);
			}
		});
	}

	public String encode(String value) throws UnsupportedEncodingException {
		if (value != null) {
			return StringUtility.encode(value);
		} else {
			return "";
		}
	}
	
	/******************* APIs ***********************/
	
	/**
	 * Ham API Dang ky tai khoan moi
	 * @method POST
	 */
	public static void register(Activity activity, String username, String password, String email,
			final ResponseListener responseListener) throws UnsupportedEncodingException{
		String module = ParameterFactory.encode("Register");
		
		String url =  Constants.APP_DOMAIN + Constants.API_PATH + module;
		RequestParams params = new RequestParams();
		params.put(Constants.PARAM_REQUEST_USERNAME, username);
		params.put(Constants.PARAM_REQUEST_PASSWORD, password);
		params.put(Constants.PARAM_REQUEST_EMAIL, email);
		
		// POST to server
		requestProcess(url, params, activity, false, responseListener);
	}
	
	/**
	 * Ham API Thay doi mat khau
	 * @method POST
	 */
	public static void changePassword(Activity activity, String oldPass, String newPass, String accessToken,
			final ResponseListener responseListener) throws UnsupportedEncodingException{
		String module = ParameterFactory.encode("editPassword");
		String url =  Constants.APP_DOMAIN + Constants.API_PATH + module;
		
		RequestParams params = new RequestParams();
		params.put(Constants.PARAM_REQUEST_OLD_PASS, oldPass);
		params.put(Constants.PARAM_REQUEST_NEW_PASS, newPass);
		params.put(Constants.PARAM_REQUEST_ACCESS_TOKEN, accessToken);
		
		// POST to server
		requestProcess(url, params, activity, false, responseListener);
		Log.e("params editPass", Constants.PARAM_REQUEST_OLD_PASS + "=" + oldPass + ", " +
		Constants.PARAM_REQUEST_NEW_PASS +"=" + newPass + ", " +
		Constants.PARAM_REQUEST_ACCESS_TOKEN +"="+ accessToken);
	}

	public static void login(Activity activity, String username, String password, ResponseListener responseListener) {
		String url = "";
		try {
			url = ParameterFactory.createURLLogin(username, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcessLogin(url, activity, false, responseListener);
	}
	
	public static void getPaymentApprove(final Activity activity,
			final ResponseListener responseListener) {
		String url = Constants.APP_DOMAIN + "/confMob/android_1.0.txt";
		requestProcess(url, activity, false, responseListener);
	}
	
	public static void getIntroduction(final Activity activity,
			final ResponseListener responseListener) {
		String url = Constants.APP_DOMAIN + "/confMob/gioithieu.txt";
		requestProcess(url, activity, false, responseListener);
	}
	// Get Home Detail (list news in home)
	public static void getHomeDetail(final Activity activity,
			final ResponseListener responseListener) {
		
		String url = "";
		try {
			url = ParameterFactory.createURLGetHomeDetail();
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
		
	}
	
	/**
	 * Lay danh sach Nguoi mau theo type
	 * @param activity
	 * @param type = 0: ALL / 1: NEW / 2: HOT / 3: TOP
	 * @param page
	 * @param pageSize
	 * @param responseListener
	 */
	public static void getModels(final Activity activity, int type, int page, int pageSize,
			final ResponseListener responseListener) {
		
		String url = "";
		try {
			url = ParameterFactory.createURLGetModels(type, page, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		requestProcess(url, activity, false, responseListener);
	}
	
	/**
	 * Lay thong tin chi tiet cua Nguoi mau
	 * @param activity
	 * @param model_id 
	 */
	public static void getModelDetail(final Activity activity, String model_id, final ResponseListener responseListener) {
		String url = "";
		try {
			url = ParameterFactory.createURLGetModelDetail(model_id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
	}
	
	/**
	 * Lay profile cua Nguoi mau
	 * @param activity
	 * @param model_id 
	 */
	public static void getModelProfile(final Activity activity, String model_id, final ResponseListener responseListener) {
		String url = "";
		try {
			url = ParameterFactory.createURLGetModelProfile(model_id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
	}
	
	/**
	 * Lay danh sach cac comments theo type
	 * @param activity
	 * @param typeComment = 1: Model | 2: Album | 3: Video
	 * @param id
	 * @param pageSize 
	 * @param page 
	 * @param responseListener
	 */
	public static void getComments(final Activity activity, int typeComment, String id, int page, int pageSize, final ResponseListener responseListener) {
		String url = "";
		try {
			url = ParameterFactory.createURLGetComments(typeComment, id, page, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
	}
	
	/**
	 * Lay danh sach Video
	 * @param activity
	 * @param typeVideo = 0: ALL / 1: NEW / 2: HOT / 3: TOP
	 * @param page
	 * @param pageSize
	 * @param responseListener
	 */
	public static void getVideosNormal(final Activity activity, int typeVideo, int page, int pageSize,
			final ResponseListener responseListener) {
		
		String url = "";
		try {
			url = ParameterFactory.createURLGetVideosNormal(typeVideo, page, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
		
	}
	
	/**
	 * Lay danh sach Video cua Model
	 * @param activity
	 * @param modelId
	 * @param page
	 * @param pageSize
	 * @param responseListener
	 */
	public static void getVideosOfModel(final Activity activity, String modelId, int page, int pageSize,
			final ResponseListener responseListener) {
		
		String url = "";
		try {
			url = ParameterFactory.createURLGetVideosOfModel(modelId, page, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
		
	}
	
	/**
	 * Lay chi tiet cua 1 video
	 * @param activity
	 * @param videoId
	 * @param responseListener
	 */
	public static void getVideoDetail(final Activity activity, String videoId,
			final ResponseListener responseListener) {
		
		String url = "";
		String token = SharePreference.getInstance(activity).getAccessToken();
		try {
			url = ParameterFactory.createURLGetVideoDetail(videoId, token);
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
		
	}
	
	/**
	 * Lay danh sach Album
	 * @param activity
	 * @param typeAlbum = 0: ALL / 1: NEW / 2: HOT / 3: TOP
	 * @param page
	 * @param pageSize
	 * @param responseListener
	 */
	public static void getAlbumsNormal(final Activity activity, int typeAlbum, int page, int pageSize,
			final ResponseListener responseListener) {
		
		String url = "";
		try {
			url = ParameterFactory.createURLGetAlbumsNormal(typeAlbum, page, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
		
	}
	
	/**
	 * Lay danh sach Album cua Model
	 * @param activity
	 * @param modelId
	 * @param page
	 * @param pageSize
	 * @param responseListener
	 */
	public static void getAlbumsOfModel(final Activity activity, String modelId, int page, int pageSize,
			final ResponseListener responseListener) {
		
		String url = "";
		try {
			url = ParameterFactory.createURLGetAlbumsOfModel(modelId, page, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
		
	}
	
	/**
	 * Lay thong tin chi tiet cua Album
	 * @param activity
	 * @param album_id 
	 */
	public static void getAlbumDetail(final Activity activity, String album_id, final ResponseListener responseListener) {
		String url = "";
		String token = SharePreference.getInstance(activity).getAccessToken();
		try {
			url = ParameterFactory.createURLGetAlbumDetail(album_id, token);
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
	}
	
	/**
	 * Tao URL lay danh sach Tin tuc, Cau chuyen, Su kien Normal
	 * @param activity
	 * @param type = 1: Tin tuc | = 2: Cau chuyen | = 3: Su kien
	 * @param page
	 * @param pageSize
	 * @param responseListener
	 */
	public static void getArticlesNormal(final Activity activity, int type, int page, int pageSize,
			final ResponseListener responseListener) {
		
		String url = "";
		try {
			url = ParameterFactory.createURLGetArticlesNormal(type, page, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
		
	}
	
	/**
	 * Tao URL lay CHI TIET danh sach Tin tuc, Cau chuyen, Su kien Normal
	 * @param activity
	 * @param id
	 * @param responseListener
	 */
	public static void getNewDetail(final Activity activity, String id,
			final ResponseListener responseListener) {
		
		String url = "";
		try {
			url = ParameterFactory.createURLGetNewDetail(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
		
	}
	
	/**
	 * Tao URL lay danh sach Tin tuc, Cau chuyen, Su kien cua Model
	 * @param activity
	 * @param type = 1: Tin tuc | = 2: Cau chuyen | = 3: Su kien
	 * @param modelId Cac Tin tuc, Cau chuyen, Su kien lien quan den model c� modelId nay
	 * @param page
	 * @param pageSize
	 * @param responseListener
	 */
	public static void getArticlesOfModel(final Activity activity, int type, String modelId, int page, int pageSize,
			final ResponseListener responseListener) {
		
		String url = "";
		try {
			url = ParameterFactory.createURLGetArticlesOfModel(type, modelId, page, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
		
	}
	
	/**
	 * Lay danh sach Lien quan (De nghi)
	 * @param activity
	 * @param type 1: Video | 2: Model | 3: Album | 4: News | 5: Story | 6: Event
	 * @param id
	 * @param page
	 * @param pageSize
	 * @param responseListener
	 */
	public static void getRelation(final Activity activity, int type, String id, int page, int pageSize,
			final ResponseListener responseListener) {
		
		String url = "";
		try {
			url = ParameterFactory.createURLGetRelation(type, id, page, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
		
	}
	
	/**
	 * Tim kiem noi dung theo content va type
	 * @param activity
	 * @param typeSearch 1: Model | 2: Video | 3: Album | 4: News | 5: Story | 6: Event
	 * @param keyword
	 * @param page
	 * @param pageSize
	 * @param responseListener
	 */
	public static void getSearchContent(final Activity activity, int typeSearch, String keyword, int page, int pageSize,
			final ResponseListener responseListener) {
		
		String url = "";
		try {
			url = ParameterFactory.createURLGetSearchContent(typeSearch, keyword, page, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
		
	}
	
	/**
	 * Post comment
	 * @param activity
	 * @param comment 
	 */
	public static void postComment(final Activity activity, int commentType, String objId, String comment,
			final ResponseListener responseListener) {
		if (comment != null && comment != "") {
			String url = null;
			try {
				url = ParameterFactory.createURLPostComment(commentType, objId, comment, SharePreference.getInstance(activity).getAccessToken());
			} catch (Exception e) {
				e.printStackTrace();
			}

			requestProcess(url, activity, false, responseListener);
		}
	}
	
	/**
	 * Lay danh sach noi dung Free
	 * @param activity
	 * @param page
	 * @param pageSize
	 * @param responseListener
	 */
	public static void getFree(final Activity activity, ResponseListener responseListener) {
		String url = "";
		try {
			url = ParameterFactory.createURLGetFree();
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
	}
	
	/**
	 * Lay danh sach noi dung Update
	 * @param activity
	 * @param responseListener
	 */
	public static void getUpdate(final Activity activity, int page, int pageSize, ResponseListener responseListener) {
		String url = "";
		try {
			url = ParameterFactory.createURLGetUpdate(page, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		requestProcess(url, activity, false, responseListener);
	}
	
	/**
	 * Ham API get ALl User Info
	 * @method POST
	 */
	public static void getAllInforUser(Activity activity, final ResponseListener responseListener) {
		String module = "GetAllInforUser";
		String accessToken = SharePreference.getInstance(activity).getAccessToken();
		
		String url =  Constants.APP_DOMAIN + Constants.API_PATH + module +
				"?" + Constants.PARAM_REQUEST_ACCESS_TOKEN + "=" + accessToken;
		
		requestProcess(url, activity, false, responseListener);
	}

	public static void getCityData(Activity activity, final ResponseListener responseListener) {
		String module = "GetCity";
		String url = Constants.APP_DOMAIN + Constants.API_PATH + module;
		requestProcess(url, activity, false, responseListener);
	}
	public static void subScribe(Activity activity, String otp, ResponseListener responseListener) {
		String url = ParameterFactory.createURLSubScribe();

		String token = SharePreference.getInstance(activity).getAccessToken();
		RequestParams parameters = new RequestParams();
		parameters.put(Constants.PARAM_REQUEST_OTP, otp);
		parameters.put(Constants.PARAM_REQUEST_ACCESS_TOKEN, token);
		
		requestProcess(url, parameters, activity, false, responseListener);
	}
	
	public static void chargeBySub(Activity activity,  String phoneNumberNew, ResponseListener responseListener) {
		String token = SharePreference.getInstance(activity).getAccessToken();
		
		String url = ParameterFactory.createURLChargeBySub();
		
		RequestParams parameters = new RequestParams();
		parameters.put(Constants.PARAM_REQUEST_PHONE, phoneNumberNew);
		parameters.put(Constants.PARAM_REQUEST_ACCESS_TOKEN, token);
		
		requestProcess(url, parameters, activity, false, responseListener);
	}
	
	public static void chargeBySub(Activity activity, String phoneNumberNew, String otp, ResponseListener responseListener) {
		String token = SharePreference.getInstance(activity).getAccessToken();
		
		String url = ParameterFactory.createURLChargeBySub();
		
		RequestParams parameters = new RequestParams();
		parameters.put(Constants.PARAM_REQUEST_PHONE, phoneNumberNew);
		parameters.put(Constants.PARAM_REQUEST_OTP, otp);
		parameters.put(Constants.PARAM_REQUEST_ACCESS_TOKEN, token);
		
		requestProcess(url, parameters, activity, false, responseListener);
	}

	public static void chargeByCard(Activity activity, String code, String series, String operator, ResponseListener responseListener) {
		String token = SharePreference.getInstance(activity).getAccessToken();
		
		String url = ParameterFactory.createURLChargeByCard();
		
		RequestParams parameters = new RequestParams();
		parameters.put(Constants.PARAM_REQUEST_CODE, code);
		parameters.put(Constants.PARAM_REQUEST_SERIES, series);
		parameters.put(Constants.PARAM_REQUEST_OPERATOR, operator);
		parameters.put(Constants.PARAM_REQUEST_ACCESS_TOKEN, token);
		
		requestProcess(url, parameters, activity, false, responseListener);
	}

	public static void changePhoneNumber(Activity activity, int changeType, String phoneNumberNew, String otp,
			ResponseListener responseListener) {
		String token = SharePreference.getInstance(activity).getAccessToken();
		
		String url = ParameterFactory.createURLChangePhoneNumber();
		
		RequestParams parameters = new RequestParams();
		parameters.put(Constants.PARAM_REQUEST_ACCESS_TOKEN, token);
		parameters.put(Constants.PARAM_REQUEST_PHONE, phoneNumberNew);
		
		if (changeType == PaymentControl.CHANGE_PHONE_OTP) {
			parameters.put(Constants.PARAM_REQUEST_OTP, otp);
		}
		
		requestProcess(url, parameters, activity, false, responseListener);
	}

	/**
	 * Cap nhat thong tin ca nhan [tab Sua Thong Tin Ca nhan]
	 * @param activity
	 * @param newEmail
	 * @param newFullName
	 * @param newBirthday
	 * @param gender
	 * @param responseListener
	 */
	public static void editProfile(Activity activity, String newEmail,
			String newFullName, String newBirthday, int newGender,String cityId,
			ResponseListener responseListener) {
		
		String module = "editProfile";
		String accessToken = SharePreference.getInstance(activity).getAccessToken();
		
		String url =  Constants.APP_DOMAIN + Constants.API_PATH + module;
				
		RequestParams parameters = new RequestParams();
		parameters.put(Constants.PARAM_REQUEST_ACCESS_TOKEN, accessToken);
		parameters.put(Constants.PARAM_REQUEST_EMAIL, newEmail);
		parameters.put(Constants.PARAM_REQUEST_FULLNAME, newFullName);
		parameters.put(Constants.PARAM_REQUEST_GENDER, newGender + "");
		parameters.put(Constants.PARAM_REQUEST_BIRTHDAY, newBirthday);
		parameters.put(Constants.PARAM_REQUEST_CITY, cityId);
		
		requestProcess(url, parameters, activity, false, responseListener);
	}
	
	public static void getEmails(Activity activity, int page, int pageSize, ResponseListener responseListener) {
		String accessToken = SharePreference.getInstance(activity).getAccessToken();
		
		String url = ParameterFactory.createURLGetEmails(accessToken, page, pageSize);

		requestProcess(url, activity, false, responseListener);
	}
	
	public static void getDetailEmails(Activity activity,String emailId, ResponseListener responseListener) {
		String accessToken = SharePreference.getInstance(activity).getAccessToken();
		
		String url = ParameterFactory.createURLGetDetailEmails(accessToken,emailId);

		requestProcess(url, activity, false, responseListener);
	}

	public static void getPointUser(Activity activity, ResponseListener responseListener) {
		String accessToken = SharePreference.getInstance(activity).getAccessToken();
		
		String url = ParameterFactory.createURLGetPointUser(accessToken);

		requestProcess(url, activity, false, responseListener);
	}

	public static void getHistory(Activity activity, ResponseListener responseListener) {
		String accessToken = SharePreference.getInstance(activity).getAccessToken();
		
		String url = ParameterFactory.createURLGetHistory(accessToken);

		requestProcess(url, activity, false, responseListener);
	}
	
	/******************* End APIs ***********************/
}
